package cn.tedu.front.search.dao.search.impl;

import cn.tedu.common.pojo.vo.PageData;
import cn.tedu.front.search.dao.search.ICompanyCustomSearchRepository;
import cn.tedu.front.search.dao.search.ICompanySearchRepository;
import cn.tedu.front.search.pojo.po.CompanyPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class CompanySearchRepositoryImpl implements ICompanySearchRepository {
    @Autowired
    private ICompanyCustomSearchRepository companyElasticSearch;

    @Override
    public PageData<CompanyPO> search(String keyword, Integer pageNum, Integer pageSize) {
        pageNum--;
        //Pageable 的pageNum从0开始
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        SearchPage<CompanyPO> searchHits = companyElasticSearch.customSearchCompanyPO(keyword, pageable);
        SearchHits<CompanyPO> hits = searchHits.getSearchHits();

        PageData<CompanyPO> pageData = new PageData<>();
        pageData.setCurrentPage(pageNum++);
        pageData.setPageSize(pageSize);
        pageData.setMaxPage(searchHits.getTotalPages());
        pageData.setTotal(searchHits.getSearchHits().getTotalHits());

        List<CompanyPO> list = new ArrayList<>();
        for (SearchHit<CompanyPO> hit : hits) {
            CompanyPO hitContent = hit.getContent();
            list.add(hitContent);
        }
      pageData.setList(list);
        return pageData;


    }
}
